package com.xue.utils;

import java.util.concurrent.*;

/**
 * @author xue
 * @create 2022-09-19 9:58
 */
public class ThreadPoolUtils {

    /**
     * 获取当前机器的核数, 不一定准确 请根据实际场景 CPU密集 || IO 密集
     */
    public static final int CPU_NUM = Runtime.getRuntime().availableProcessors();

    private volatile static ThreadPoolExecutor threadPool;

    public static void executor(Runnable runnable) {
        getThreadPoolExecutor().execute(runnable);
    }

    public static <T> Future<T> submit(Callable<T> callable) {
        return getThreadPoolExecutor().submit(callable);
    }

    public static ThreadFactory getThreadFactory() {
        return getThreadPoolExecutor().getThreadFactory();
    }

    public static ThreadPoolExecutor getThreadPoolExecutor() {
        if (threadPool == null) {
            synchronized (ThreadPoolUtils.class) {
                if (threadPool == null) {
                    threadPool = new ThreadPoolExecutor(CPU_NUM, CPU_NUM * 2, 60, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(500), new ThreadPoolExecutor.CallerRunsPolicy());
                }
            }
        }
        return threadPool;
    }


}
